package ch.unibe.jogeasy;

import android.app.ProgressDialog;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ListView;

public class MyTouchListener implements OnTouchListener{
	private TracksActivity ta;
	/**
	 * Recognizer task, which runs in a worker thread.
	 */
	RecognizerTask rec;
	/**
	 * Are we listening?
	 */
	boolean listening = false;
	
	/**
	 * Thread in which the recognizer task runs.
	 */
	Thread rec_thread;
	/**
	 * Progress dialog for final recognition.
	 */
	ProgressDialog rec_dialog;
	MyListener recognitionListener;
	
	public MyTouchListener(TracksActivity ta){
		this.ta = ta;
		recognitionListener = new MyListener(ta);
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		//int pos = (Integer)v.getTag();
		System.out.println("The v " +v);
		if (v.getClass() == ListView.class) {
			ListView lv = (ListView)v;
			lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			
			System.out.println("List View Position" + lv.getCheckedItemPosition());
		}
		
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			this.rec = new RecognizerTask();
			this.rec_thread = new Thread(this.rec);
			this.listening = false;
			this.rec.setRecognitionListener(recognitionListener);
			this.rec_thread.start();
			
			this.listening = true;
			System.out.println("we are in action down");
			this.rec.start();
			break;
		case MotionEvent.ACTION_UP:

			System.out.println("we are in action up");
			if (this.listening) {
				System.out.println("in if listening");
				Log.d(getClass().getName(), "Showing Dialog");
				this.rec_dialog = ProgressDialog.show(ta, "", "Recognizing speech...", true);
				this.rec_dialog.setCancelable(false);
				this.listening = false;
			}
			this.rec.stop();
			recognitionListener.setDialog(rec_dialog);
			System.out.println("it stopped recording");
			break;
		default:
			;
		}
		/* Let the button handle its own state */
		return false;
	}

}
